<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="活动名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入活动名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属分类" prop="categoryId">
        <el-select v-model="queryParams.categoryId" placeholder="请选择所属分类" clearable>
          <el-option
            v-for="category in categoryList"
            :key="category.id"
            :label="category.name"
            :value="category.id"
          />
        </el-select>
       </el-form-item>
       <el-form-item label="所属地区" prop="regionId">
        <el-select v-model="queryParams.regionId" placeholder="请选择所属地区" clearable>
          <el-option
            v-for="region in regionList"
            :key="region.id"
            :label="region.name"
            :value="region.id"
          />
        </el-select>
       </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker clearable
          v-model="queryParams.startTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker clearable
          v-model="queryParams.endTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="活动地址" prop="location">
        <el-input
          v-model="queryParams.location"
          placeholder="请输入活动地址"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="主办方" prop="organizer">
        <el-input
          v-model="queryParams.organizer"
          placeholder="请输入主办方"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['management:event:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['management:event:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['management:event:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['management:event:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="eventList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" width="80">
        <template #default="scope">
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="活动名称" align="center" prop="name" />
      <el-table-column label="所属分类" align="center" prop="categoryId">
        <template #default="scope">
          <span>{{ categoryNameById[scope.row.categoryId] || scope.row.categoryId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属地区" align="center" prop="regionId">
        <template #default="scope">
          <span>{{ regionNameById[scope.row.regionId] || scope.row.regionId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="活动地址" align="center" prop="location" />
      <el-table-column label="主办方" align="center" prop="organizer" />
      <el-table-column label="活动简介" align="center" prop="introduction">
        <template #default="scope">
          <el-tooltip effect="dark" placement="top" :content="scope.row.introduction">
            <div class="clamp-2">{{ scope.row.introduction }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag :type="Number(scope.row.status) === 1 ? 'success' : 'info'">{{ Number(scope.row.status) === 1 ? '启用' : '禁用' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="封面图片" align="center" prop="image" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.image" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="详细内容" align="center" width="100">
        <template #default="scope">
          <el-button 
            type="primary" 
            size="small" 
            @click="handleViewDetail(scope.row)"
          >
            查看详情
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['management:event:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['management:event:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改活动管理对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-tabs v-model="activeTab" type="border-card">
        <el-tab-pane label="基本信息" name="basic">
          <el-form ref="eventRef" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="活动名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入活动名称" />
            </el-form-item>
            <el-form-item label="所属分类" prop="categoryId">
              <el-select v-model="form.categoryId" placeholder="请选择所属分类" style="width: 100%">
                <el-option
                  v-for="category in categoryList"
                  :key="category.id"
                  :label="category.name"
                  :value="category.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="所属地区" prop="regionId">
              <el-select v-model="form.regionId" placeholder="请选择所属地区" style="width: 100%">
                <el-option
                  v-for="region in regionList"
                  :key="region.id"
                  :label="region.name"
                  :value="region.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker clearable
                v-model="form.startTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择开始时间">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker clearable
                v-model="form.endTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择结束时间">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="活动地址" prop="location">
              <el-input v-model="form.location" placeholder="请输入活动地址" />
            </el-form-item>
            <el-form-item label="主办方" prop="organizer">
              <el-input v-model="form.organizer" placeholder="请输入主办方" />
            </el-form-item>
            <el-form-item label="活动简介" prop="introduction">
              <el-input v-model="form.introduction" type="textarea" placeholder="请输入内容" />
            </el-form-item>
            <el-form-item label="封面图片" prop="image">
              <image-upload v-model="form.image" :limit="1" :key="dialogKey"/>
            </el-form-item>
            <el-form-item label="展示状态" prop="status" v-if="form.id">
              <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="启用" :value="1" />
                <el-option label="禁用" :value="0" />
              </el-select>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="详情内容" name="detail">
          <el-form ref="detailRef" :model="detailForm" label-width="80px">
            <el-form-item label="详细介绍">
              <WangEditor 
                v-model="detailForm.description" 
                :height="300" 
                placeholder="请输入详细介绍内容"
                :key="`editor-${detailDialogKey}`"
                ref="editorRef"
              />
            </el-form-item>
            <el-form-item label="相关图片">
              <image-upload 
                v-model="detailForm.images" 
                :limit="10" 
                :multiple="true"
                :key="detailDialogKey"
                list-type="picture-card"
              />
              <div class="form-tip">支持上传多张图片，最多10张</div>
            </el-form-item>
            <el-form-item label="相关视频">
              <file-upload 
                v-model="detailForm.videos" 
                :limit="5"
                :multiple="true"
                :file-type="['mp4', 'avi', 'mov', 'wmv', 'flv', 'webm']"
                :key="detailDialogKey"
              />
              <div class="form-tip">支持上传多个视频文件，最多5个，支持格式：mp4、avi、mov、wmv、flv、webm</div>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Event">
import { listEvent, getEvent, delEvent, addEvent, updateEvent, getEventDetail } from "@/api/management/event"
import { listEventCategory } from "@/api/management/EventCategory"
import { listEventRegion } from "@/api/management/EventRegion"
import { useRouter } from "vue-router"
import WangEditor from '@/components/WangEditor/index.vue'

const { proxy } = getCurrentInstance()

const eventList = ref([])
const categoryList = ref([])
const regionList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const router = useRouter()
const dialogKey = ref(0)
const detailDialogKey = ref(0)
const activeTab = ref('basic')
const detailForm = ref({
  description: '',
  images: [],
  videos: []
})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    categoryId: null,
    regionId: null,
    startTime: null,
    endTime: null,
    location: null,
    organizer: null,
    status: null,
  },
  rules: {
    name: [
      { required: true, message: "活动名称不能为空", trigger: "blur" }
    ],
    categoryId: [
      { required: true, message: "所属分类不能为空", trigger: "change" }
    ],
    regionId: [
      { required: true, message: "所属地区不能为空", trigger: "change" }
    ],
    startTime: [
      { required: true, message: "活动开始时间不能为空", trigger: "blur" }
    ],
    endTime: [
      { required: true, message: "活动结束时间不能为空", trigger: "blur" }
    ],
    location: [
      { required: true, message: "活动地址不能为空", trigger: "blur" }
    ],
    organizer: [
      { required: true, message: "主办方不能为空", trigger: "blur" }
    ],
    introduction: [
      { required: true, message: "活动简介不能为空", trigger: "blur" }
    ],
    image: [
      { required: true, message: "封面图片不能为空", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询活动管理列表 */
function getList() {
  loading.value = true
  const params = { ...queryParams.value }
  if (params.startTime) params.startTime = params.startTime + ' 00:00:00'
  if (params.endTime) params.endTime = params.endTime + ' 23:59:59'
  listEvent(params).then(response => {
    // 规范化封面图片字段，兼容字符串、JSON 字符串数组、数组三种格式
    const normalizeImage = (img) => {
      if (!img) return '';
      if (Array.isArray(img)) return img[0] || '';
      if (typeof img === 'string') {
        // JSON 字符串数组
        if (img.startsWith('[')) {
          try {
            const arr = JSON.parse(img);
            if (Array.isArray(arr)) return arr[0] || '';
          } catch (e) {
            // 非 JSON，则直接返回原字符串
          }
        }
        return img;
      }
      return '';
    };
    eventList.value = (response.rows || []).map(r => ({
      ...r,
      image: normalizeImage(r.image)
    }));
    total.value = response.total
    loading.value = false
  })
}

const categoryNameById = computed(() => Object.fromEntries((categoryList.value || []).map(c => [c.id, c.name])))
const regionNameById = computed(() => Object.fromEntries((regionList.value || []).map(r => [r.id, r.name])))

/** 获取分类列表 */
function getCategoryList() {
  listEventCategory({ pageNum: 1, pageSize: 999 }).then(response => {
    categoryList.value = response.rows || response.data || []
  })
}

/** 获取地区列表 */
function getRegionList() {
  listEventRegion({ pageNum: 1, pageSize: 999 }).then(response => {
    regionList.value = response.rows || response.data || []
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    categoryId: null,
    regionId: null,
    startTime: null,
    endTime: null,
    location: null,
    organizer: null,
    introduction: null,
    status: null,
    createdAt: null,
    updatedAt: null,
    image: null
  }
  nextTick(() => {
    detailForm.value = { description: '', images: [], videos: [] }
  })
  activeTab.value = 'basic'
  proxy.resetForm("eventRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
  getCategoryList()
  getRegionList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  dialogKey.value++
  detailDialogKey.value++
  nextTick(() => {
    open.value = true
    title.value = "添加活动管理"
    activeTab.value = 'basic'
  })
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  dialogKey.value++
  detailDialogKey.value++
  const _id = row.id || ids.value
  getEventDetail(_id).then(response => {
    const data = response.data || {}
    form.value = {
      id: data.id,
      name: data.name,
      categoryId: data.categoryId,
      regionId: data.regionId,
      startTime: data.startTime ? ('' + data.startTime).slice(0, 10) : null,
      endTime: data.endTime ? ('' + data.endTime).slice(0, 10) : null,
      location: data.location,
      organizer: data.organizer,
      introduction: data.introduction,
      image: data.image,
      status: data.status != null ? Number(data.status) : null
    }
    const parseMaybeList = (val) => {
      if (!val) return []
      if (Array.isArray(val)) return val
      if (typeof val === 'string') {
        const s = val.trim().replace(/^"|"$/g, '')
        if (!s) return []
        if (s.startsWith('[')) {
          try { const arr = JSON.parse(s); return Array.isArray(arr) ? arr : [] } catch {}
        }
        return s.split(',').map(x => x.trim()).filter(Boolean)
      }
      return []
    }
    detailForm.value = {
      description: data.description || '',
      images: parseMaybeList(data.images),
      videos: parseMaybeList(data.videos)
    }
    nextTick(() => {
      open.value = true
      title.value = "修改活动管理"
      activeTab.value = 'basic'
    })
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["eventRef"].validate(valid => {
    if (valid) {
      // 规范化图片/视频：将对象数组转换为URL数组
      const toUrlArray = (arr) => {
        if (!arr) return []
        if (Array.isArray(arr)) {
          return arr.map(item => {
            if (typeof item === 'string') return item
            // 常见返回：{ url } 或 { response: { url } } 或 { name, url }
            if (item && typeof item === 'object') {
              if (item.url) return item.url
              if (item.response && (item.response.url || item.response.data || item.response[0])) {
                // 尝试从响应中取url或第一个文件的url
                if (item.response.url) return item.response.url
                if (Array.isArray(item.response.data)) {
                  const first = item.response.data[0]
                  if (first && first.url) return first.url
                }
                if (Array.isArray(item.response)) {
                  const first = item.response[0]
                  if (first && first.url) return first.url
                }
              }
            }
            return null
          }).filter(Boolean)
        }
        // 如果是字符串（可能已是JSON），交给后端规范化
        return arr
      }

      const imgUrls = toUrlArray(detailForm.value.images)
      const vidUrls = toUrlArray(detailForm.value.videos)

      const submitData = {
        ...form.value,
        eventDetail: {
          description: detailForm.value.description || '',
          images: Array.isArray(imgUrls) ? JSON.stringify(imgUrls) : (imgUrls || '[]'),
          videos: Array.isArray(vidUrls) ? JSON.stringify(vidUrls) : (vidUrls || '[]')
        }
      }

      if (form.value.id != null) {
        updateEvent(submitData).then(() => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          detailDialogKey.value++
          getList()
        })
      } else {
        delete submitData.status
        addEvent(submitData).then(() => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  // 计算页面序号
  let displayNumbers = []
  if (ids.value && ids.value.length > 0) {
    ids.value.forEach(id => {
      const index = eventList.value.findIndex(item => item.id === id)
      if (index !== -1) {
        const pageNumber = (queryParams.value.pageNum - 1) * queryParams.value.pageSize + index + 1
        displayNumbers.push(pageNumber)
      }
    })
  } else if (row) {
    const index = eventList.value.findIndex(item => item.id === row.id)
    if (index !== -1) {
      const pageNumber = (queryParams.value.pageNum - 1) * queryParams.value.pageSize + index + 1
      displayNumbers.push(pageNumber)
    }
  }
  const _ids = (ids.value && ids.value.length > 0) ? ids.value : (row ? row.id : [])
  const displayText = displayNumbers.length > 1 ? displayNumbers.join('、') : displayNumbers[0] || _ids
  proxy.$modal.confirm('是否确认删除活动序号为"' + displayText + '"的数据项？').then(function() {
    return delEvent(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  const params = { ...queryParams.value }
  if (params.startTime) params.startTime = params.startTime + ' 00:00:00'
  if (params.endTime) params.endTime = params.endTime + ' 23:59:59'
  proxy.download('management/event/export', params, `event_${new Date().getTime()}.xlsx`)
}

/** 查看详情按钮操作 */
function handleViewDetail(row) {
  router.push({
    path: '/management/event-detail/index',
    query: { id: row.id }
  })
}

getList()
getCategoryList()
getRegionList()
</script>

<style scoped>
.clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: normal;
}
</style>
